<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page import="java.util.List" %>
<%@ page import="com.google.appengine.api.users.User" %>
<%@ page import="com.google.appengine.api.users.UserService" %>
<%@ page import="com.google.appengine.api.users.UserServiceFactory" %>
<%@ page import="com.google.appengine.api.datastore.DatastoreServiceFactory" %>
<%@ page import="com.google.appengine.api.datastore.DatastoreService" %>
<%@ page import="com.google.appengine.api.datastore.Query" %>
<%@ page import="com.google.appengine.api.datastore.Entity" %>
<%@ page import="com.google.appengine.api.datastore.FetchOptions" %>
<%@ page import="com.google.appengine.api.datastore.Key" %>
<%@ page import="com.google.appengine.api.datastore.KeyFactory" %>
<%@ page import="data.Book" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>

<html>

  <body>
  	<%
    	String bookStore = request.getParameter("bookStore");
    	if (bookStore == null) 
        	bookStore = "default";
    	
    	pageContext.setAttribute("bookStore", bookStore);
    	UserService userService = UserServiceFactory.getUserService();
    	User user = userService.getCurrentUser();
    	if (user != null) 
      		pageContext.setAttribute("user", user);
    %>
    
    <form action="/addBook" method="post">
      <div><textarea name="content" rows="3" cols="60"></textarea></div>
      <div><input type="submit" value="Add Book" /></div>
      <input type="hidden" name="bookStore" value="${fn:escapeXml(bookStore)}"/>
    </form>
    
    <form action="/deleteBook" method="post">
      <div><textarea name="content" rows="1" cols="60"></textarea></div>
      <div><input type="submit" value="Delete Book By ISBN" /></div>
      <input type="hidden" name="bookStore" value="${fn:escapeXml(bookStore)}"/>
    </form>

 	<%
 		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
    	Key keyBookStore = KeyFactory.createKey("BookStore", bookStore);
    	Query query = new Query("Book", keyBookStore);
    	List<Entity> lsBook = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(5));
    	if (!lsBook.isEmpty())
    	{
    		for (Entity entBook : lsBook)
    		{
    			Book book = new Book(entBook);
    			%>
    				<p>  <%= book.toString() %> </p>
    			<%
    		}
    	}
    	else
    	{
    		%>
    			<p> Book list is empty </p>
    		<%
    	}
    %>

  </body>
</html>